﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TekaMUD.Engine.IO
{
	/// <summary>
	/// Telnet negotiation helper functions
	/// </summary>
	public class TelnetNegotiation
	{
		public static readonly byte[] TELNET_SHOW_ECHO = {0xFF, 0xFC, 0x01, 0x00}; /* IAC DO ECHO */
		public static readonly byte[] TELNET_HIDE_ECHO = {0xFF, 0xFB, 0x01, 0x00}; /* IAC DO ECHO */

		/// <summary>
		/// Escape the otherwise interpretable IAC code from a byte[] which is to be sent to a remote Telnet client
		/// </summary>
		/// <remarks>Adds a new IAC control character following the first one.</remarks>
		public byte[] EscapeIAC(byte[] buf)
		{
			bool process = false;
			uint count = 0;

			for (int i = 0; i < buf.Length; i++)
				if (buf[i] == 0xFF)
				{
					process = true;
					count++;
				}

			if (process)
			{
				byte[] newbuf = new byte[buf.Length + count];
				int j = 0;

				for (int i = 0; i < buf.Length; i++, j++)
				{
					newbuf[j] = buf[i];

					if (buf[i] == 0xFF)
						newbuf[++j] = 0xFF;
				}

				return newbuf;
			}
			else
			{
				return buf;
			}
		}


	}
}
